import { Module, DynamicModule as NestDynamicModule } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import { SharedModule } from '@/shared.module';
import { APP_GUARD } from '@nestjs/core';
import { PermissionGuard } from './permission.guard'
import { loadControllers } from './dynamic-loadet'
import { join } from 'path';




@Module({})
export class DynamicModule {
  static async register(): Promise<NestDynamicModule> {

    const controllers = [...loadControllers(join(__dirname, 'controller'), join(__dirname)),];

    const providers = [{
      provide: APP_GUARD,
      useClass: PermissionGuard,  // 全局启用权限守卫器
    },];

    const controllerDir = path.join(__dirname, './controller');

    // 递归遍历文件夹
    const readDirRecursive = (dirPath: string, routePrefix: string) => {
      const files = fs.readdirSync(dirPath);
      for (const file of files) {
        const fullPath = path.join(dirPath, file);
        const stat = fs.statSync(fullPath);

        if (stat.isDirectory()) {
          // 如果是子目录，递归调用并传入当前目录名作为路由前缀
          readDirRecursive(fullPath, `${routePrefix}/${file}`);
        } else if (file.endsWith('.service.js')) {
          // 如果是 service 文件，加载并添加到 providers 中
          import(fullPath).then((serviceModule) => {
            const serviceName = Object.keys(serviceModule)[0];
            providers.push(serviceModule[serviceName]);
          });
        }
      }
    };

    try {
      // 从根控制器目录开始，路由前缀为空字符串
      readDirRecursive(controllerDir, '');


      // 等待所有异步导入完成后返回模块
      await Promise.all([
        ...providers.map((provider) => provider),
      ]);

      return {
        module: DynamicModule,
        imports: [SharedModule],
        controllers,
        providers,
      };
    } catch (error) {
      console.error('异步加载控制器失败:', error);
      return {
        module: DynamicModule,
        controllers: [],
        providers: [],
      };
    }
  }
}
